<template>
  <div :class="'style_' + table.name">
    <!-- :data="table.tableList" -->
    <vxe-table
      :ref="`xTable${table.name}`"
      :align="allAlign"
      border
      :height="getHeightFuc"
      highlight-current-row
      highlight-hover-row
      :loading="loading"
      :radio-config="{ highlight: true }"
      :scroll-y="{ gt: tablePage.pageSize }"
      show-header-overflow
      show-overflow
      style="overflow-y: scroll"
      @cell-click="clickOne"
      @checkbox-all="selectAllChangeEvent"
      @checkbox-change="selectChangeEvent"
      @radio-change="radioChangeEvent"
    >
      <vxe-column
        v-for="item in columnList"
        :key="item.porp"
        :field="getProps(item.porp)"
        min-width="150"
        :resizable="true"
        :sortable="item.sortable || false"
        :title="item.label"
        :type="
          item.type == 'input' ||
          item.type == 'select' ||
          item.type == 'textarea' ||
          item.type == 'textarea_in_out' ||
          item.porp == 'ACTIVE_FLAG' ||
          item.porp == 'ADVANCE_FLAG'
            ? ''
            : item.type
        "
      />
      <vxe-column
        v-if="tableOperationList.length > 0 && !table.operation"
        fixed="right"
        :title="translateTitle('Dams.ApplicationInterface.操作')"
        :width="table.width || '300'"
      >
        <template #default="{ row }">
          <!-- 修改密码这是单独的 -->
          <vxe-button v-if="userUid == row.ID" type="text" @click="pswAmend(row)">
            {{ translateTitle('Dams.ApplicationInterface.修改密码') }}
          </vxe-button>
          <template v-for="(item, index) in tableOperationList" :key="index">
            <vxe-button
              v-if="item.FUNCTION_URI == 'startUsing' && item.FUNCTION_URI != 'refresh'"
              type="text"
              @click="common_event(item.FUNCTION_URI, row)"
            >
              {{ row.ACTIVE_FLAG == 'N' ? translateTitle('Dams.ApplicationInterface.启用') : translateTitle('Dams.ApplicationInterface.禁用') }}
            </vxe-button>
            <vxe-button v-show="table.name == 't1' && item.FUNCTION_URI == 'refresh'" type="text" @click="common_event(item.FUNCTION_URI, row)">
              {{ row.API_ENABLE == 'N' ? translateTitle('Dams.ApplicationInterface.启用') : translateTitle('Dams.ApplicationInterface.刷新') }}
            </vxe-button>
            <vxe-button
              v-if="table.name == 't1' && item.FUNCTION_URI == 'portForbidden' && row.API_ENABLE === 'Y' && row.API_NAME !== '*.standard.disable.api'"
              type="text"
              @click="common_event(item.FUNCTION_URI, row)"
            >
              {{ item.BUTTON_NAME }}
            </vxe-button>
            <vxe-button
              v-if="item.FUNCTION_URI !== 'startUsing' && item.FUNCTION_URI != 'refresh' && item.FUNCTION_URI != 'portForbidden'"
              type="text"
              @click="common_event(item.FUNCTION_URI, row)"
            >
              {{ item.BUTTON_NAME }}
            </vxe-button>
          </template>
        </template>
      </vxe-column>
      <vxe-column
        v-else-if="btnFix && noOperation.indexOf(name) == -1"
        fixed="right"
        :title="translateTitle('Dams.ApplicationInterface.操作')"
        :width="table.width || '200'"
      >
        <template #default="{ row }">
          <vxe-button v-if="noEditList.indexOf(name) == -1" type="text" @click="common_event('editor', row)">
            {{ translateTitle('Dams.ApplicationInterface.编辑') }}
          </vxe-button>
          <vxe-button v-if="name !== 'LogMonitor' && name !== 'LogTestMonitor'" type="text" @click="common_event('delete', row)">
            {{ translateTitle('Dams.ApplicationInterface.删除') }}
          </vxe-button>
          <vxe-button v-if="name == 'Timer'" type="text" @click="common_event('handTrigger', row)">
            {{ translateTitle('Dams.ApplicationInterface.手动触发') }}
          </vxe-button>
          <vxe-button
            v-if="(name == 'LogMonitor' || name == 'LogTestMonitor') && (row.ADAPTER_TYPE == 'I' || row.ADAPTER_TYPE == 'R_I')"
            type="text"
            @click="common_event('retransmission', row)"
          >
            {{ translateTitle('Dams.ApplicationInterface.断点重传') }}
          </vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
    <vxe-pager
      v-if="!table.pagerOpen"
      :current-page="tablePage.limit"
      :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
      :page-size="tablePage.pageSize"
      :page-sizes="[50, 100, 150, 200]"
      :total="tablePage.count"
      @page-change="handlePageChange"
    />
  </div>
</template>

<script>
  import isEmpty from 'lodash/isEmpty'
  import { translateTitle } from '@/utils/i18n'
  export default {
    name: 'Table',
    props: {
      loading: {
        type: Boolean,
        default: false,
      },
      btnFix: {
        type: Boolean,
        default: false,
      },
      columnList: {
        type: Array,
        default: function () {
          return []
        },
      },
      tables: {
        type: Object,
        default: function () {
          return {}
        },
      },
      getHeight: {
        type: String,
        default: function () {
          return '100'
        },
      },
      name: {
        type: String,
        default: function () {
          return ''
        },
      },
    },
    data() {
      return {
        allAlign: 'center',
        tablePage: {
          count: 0,
          limit: 1,
          pageSize: 50,
        },
        noOperation: ['WmsUserRole', 'MenuButtonPulicUser', 'WmsRoleMenuButton', 'WmsUserWarehouse', 'WmsUsercargoOwner', 'WmsUserReceipts'],
        noEditList: [
          'WmsUserRole',
          'WmsUserRoleChildren',
          'WmsUserWarehouse',
          'WmsUserWarehouseChildren',
          'WmsUsercargoOwner',
          'WmsUsercargoOwnerChildren',
          'WmsUserReceipts',
          'WmsUserReceiptsChildren',
          'LogMonitor',
          'LogTestMonitor',
          'WmsRoleList',
          'LesUserRoleChildren',
          'LpmsUserRoleChildren',
          'LpmsRoleList',
          'WcsUserRoleChildren',
        ],
        table: {},
        selectRow: null,
        tableOperationList: [], //table里面操作的按钮
      }
    },
    computed: {
      getHeightFuc() {
        return `${this.getHeight - 48}`
      },
      userUid() {
        return this.$store.getters['user/uid']
      },
    },
    watch: {
      tables: {
        deep: true,
        handler(newval) {
          console.log('newval', !this.table.pagerOpen)
          this.setTable(newval)
        },
      },
    },
    created() {
      this.setTable(this.tables)
      // this.table = this.tables
      let menuBtns = this.$store.getters['user/menuBtns']
      menuBtns.forEach((row) => {
        if (this.$route.name.indexOf(row.MENU_CODE) > -1 && row.SHOW_POSTION == 'tableOperation') {
          this.tableOperationList.push(row)
        }
      })
    },
    methods: {
      getProps(prop) {
        let str = prop
        const list = ['ACTIVE_FLAG', 'BATCH_FLAG', 'UPDATE_FLAG', 'KEY_FLAG', 'IS_TRANSFER_FIELD', 'IDU_FLAG']
        if (
          list.indexOf(prop) > -1 ||
          prop === 'OUT_DATA_ACTION' ||
          prop === 'DATA_ACTION' ||
          (prop === 'TYPE' && this.name === 'MessageConfigValue') ||
          ((prop === 'ALLOW_EMPTY_FLAG' || prop === 'ADAPTER_TYPE') && (this.name === 'MessageFiledXml' || this.name === 'MessageStructure'))
        ) {
          str = prop + '_table'
        }
        return str
      },
      translateTitle,
      setTable(newval) {
        if (Object.keys(newval).length == 0) return
        this.table = newval
        this.loadData(newval)
        this.tablePage.count = newval.count
        this.tablePage.pageSize = newval.pageSize
        this.tablePage.limit = newval.limit || newval.tablePage['#LIMIT#']
      },
      getTableRef() {
        return this.$refs[`xTable${this.table.name}`]
      },
      loadData(data) {
        if (isEmpty(data)) {
          data = []
          // return
        }
        setTimeout(() => {
          this.getTableRef() && this.getTableRef().loadData(data.tableList)
          this.getTableRef().refreshColumn()
        }, 1)
        // console.log('data', data, this.getTableRef())
      },
      common_event(event_name, row) {
        this[event_name](row)
      },
      uploadPassword(row) {
        this.$pub(`${this.name}_Table_uploadPasswordBtn_uploadPassword`, row)
      },
      clearLock(row) {
        this.$pub(`${this.name}_Table_clearLockBtn_clearLock`, row)
      },
      retransmission(row) {
        this.$pub(`${this.name}_Table_resetBtn_retransmission`, row)
      },
      handTrigger(row) {
        this.$pub(`${this.name}_Table_triggerBtn_${this.name}`, row)
      },
      other(row, key) {
        this.$pub(`${this.name}_Table_otherBtn_${key}`, row)
      },
      portForbidden(row) {
        this.$pub(`${this.name}_Table_otherBtn_portForbidden`, row)
      },
      startUsing(row) {
        this.$pub(`${this.name}_Table_otherBtn_startUsing`, row)
      },
      pswAmend(row) {
        this.$pub(`${this.name}_Table_otherBtn_pswAmend`, row)
      },
      pswReset(row) {
        this.$pub(`${this.name}_Table_otherBtn_pswReset`, row)
      },
      // 编辑
      editor(row) {
        this.$pub(`${this.name}_Table_editBtn_${this.table.name}`, row)
      },
      delete(row) {
        this.$pub(`${this.name}_Table_delBtn_${this.table.name}`, row)
      },
      refresh(row) {
        this.$pub(`${this.name}_Table_RefreshBtn_${this.table.name}`, row)
      },
      // 双击行
      clickOne(e) {
        let _this = this
        let curTime = new Date().getTime()
        let lastTime = _this.lastTapDiffTime
        _this.lastTapDiffTime = curTime
        //两次点击间隔小于300ms, 认为是双击
        let diff = curTime - lastTime
        if (diff < 300) {
          console.log(`${this.name}_Table_clickOne_${this.table.name}`)
          this.$pub(`${this.name}_Table_clickOne_${this.table.name}`, e.row)
          // console.log('双击选中', e.row)
          this.$refs[`xTable${this.table.name}`].setRadioRow(e.row)
        } else {
          // 单击事件延时300毫秒执行
          _this.lastTapTimeoutFunc = setTimeout(() => {
            if (this.tables.noclick) {
              return
            }
            console.log(this.name, this.table.name)
            this.$pub(`${this.name}_Table_singleClick_${this.table.name}`, e.row)
          }, 300)
        }
      },
      radioChangeEvent({ row }) {
        this.$pub(`${this.name}_Table_radio_${this.table.name}`, row)
      },
      selectChangeEvent(data) {
        console.log('`${this.name}_Table_checkbox_${this.table.name}`', `${this.name}_Table_checkbox_${this.table.name}`)
        this.$pub(`${this.name}_Table_checkbox_${this.table.name}`, data.records)
      },
      selectAllChangeEvent(data) {
        this.$pub(`${this.name}_Table_checkboxAll_${this.table.name}`, data.records)
      },
      handlePageChange({ currentPage, pageSize }) {
        this.tablePage.limit = currentPage
        this.tablePage.pageSize = pageSize
        this.tablePage.orderNum = this.table.name //定义一个序号区别分页
        console.log(`${this.name}_Table_on_${this.table.name}`)
        this.$pub(`${this.name}_Table_on_${this.table.name}`, this.tablePage)
      },
    },
  }
</script>

<style lang="scss">
  @import '@/ve/elements/basic/uiTable/style.scss';
  @import '@/ve/styles/elements.scss';
  .vxe-button + .vxe-button,
  .vxe-button.type--text {
    margin-left: 0;
    font-size: 12px;
  }
  .vxe-button--content {
    vertical-align: baseline;
  }
</style>
<style scoped lang="scss">
  :deep() {
    .vxe-table--render-default .vxe-body--row .vxe-body--column {
      font-size: 12px;
    }
  }
</style>
